package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ndp.ec.core.api.GoogleGaService;
import com.ndp.fb.config.ConfigCentre;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.constant.ConfigConst;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.ga.EcGaCredentialExt;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.walle.business.GaAuthorizationCodeFlow;
import com.ndp.fb.model.business.vo.BaseVoParam;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.util.ResponseUtils;
import com.restfb.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by infi.he on 2016/3/18.
 */
@Controller
@RequestMapping("/ga")
public class GaOauth2Controller {

    @Autowired
    private GaAuthorizationCodeFlow baseGoogleAuthorizationCodeFlow;

    @Autowired
    private RedisClient redisClient;

    @Reference
    GoogleGaService googleGaService;

    private String redirectUri = ConfigCentre.getString(ConfigConst.GA_OAUTH_REDIRECTURI);
    private String callbakurl = ConfigCentre.getString(ConfigConst.GA_OAUTH_CALLBAKURL);

    @RequestMapping("findecgacredential")
    @ResponseBody
    public ResponseEntity<String> findecgacredential(@RequestParam(value = "param", required = true) String param, HttpServletRequest req) {

        Map<String, Object> data = new HashMap<>();

        BaseVoParam baseVoParam = JSON.parseObject(param, BaseVoParam.class);

        // 查询列表
        Integer sizeNo = baseVoParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : baseVoParam
                .getPSize();
        Integer firstResult = baseVoParam.getCPage() == null ? 0 : (baseVoParam.getCPage() - 1) * sizeNo;

        User user = (User) req.getSession().getAttribute("user");
        Pager<EcGaCredentialExt> ecGaCredentialExtPager = baseGoogleAuthorizationCodeFlow.listEcGaCredentialExt(user.getOrgId(),firstResult, sizeNo);

        // 计算分页结果
        long tSize = ecGaCredentialExtPager.getTotalSize();
        float nrOfPages = (float) tSize / sizeNo;
        int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        PageResult pageResult = new PageResult(tPage, baseVoParam.getCPage(), baseVoParam.getPSize(), tSize);
        data.put("ecGaCredentials", ecGaCredentialExtPager.getResultList());
        data.put("paginator", pageResult);

        OutputResult outputResult = ResponseUtils.bulidOutputResult(null, data);
        return ResponseUtils.returnJsonWithUTF8(outputResult);
    }


    @RequestMapping("auth")
    @ResponseBody
    public Map<String,String> auth(@RequestParam(value = "param", required = true) String param, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String redirectUrl = "";
        try {
            User user = (User) req.getSession().getAttribute("user");
            String id = req.getSession().getId();
            redisClient.set(id, param, 1L, TimeUnit.DAYS.name());
            JSONObject jsonObject = JSONObject.parseObject(param);
            String productId = jsonObject.getString("productId");
            if (StringUtils.isBlank(productId)) {
                throw new RuntimeException("productId is null");
            }
            String token = googleGaService.loadCredentialToken(user.getOrgId(), Long.valueOf(productId));
            if (token != null) {
                redirectUrl = redirectUri;
            } else {
                redirectUrl = googleGaService.newAuthorizationUrl(callbakurl);
            }
        } finally {
        }
        Map<String,String> map = new HashMap<>();
        map.put("redirectUri",redirectUrl);
        return map;
    }


    @RequestMapping("unauth")
    @ResponseBody
    public ResponseEntity<String> unauth(@RequestParam(value = "param", required = true) String param, HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            User user = (User) req.getSession().getAttribute("user");
            JSONObject jsonObject = JSONObject.parseObject(param);
            String productId = jsonObject.getString("productId");
            if (StringUtils.isBlank(productId)) {
                throw new RuntimeException("productId is null");
            }
            baseGoogleAuthorizationCodeFlow.unauth(user.getOrgId(), productId);
        } finally {
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(null, "success");
        return ResponseUtils.returnJsonWithUTF8(outputResult);
    }


    @RequestMapping(path = {"callbakurl/", "callbakurl"})
    @ResponseBody
    String callbakurl(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        StringBuffer buf = req.getRequestURL();
        if (req.getQueryString() != null) {
            buf.append('?').append(req.getQueryString());
        }
        User user = (User) req.getSession().getAttribute("user");

        String id = req.getSession().getId();
        String param = (String) redisClient.get(id);
        JSONObject jsonObject = JSONObject.parseObject(param);
        String productId = jsonObject.getString("productId");
        String trackingId = jsonObject.getString("trackingId");
        String gaUserName = jsonObject.getString("gaUserName");

        googleGaService.saveGaToken(buf.toString(),callbakurl, user, productId,trackingId, gaUserName);

        StringBuffer js = new StringBuffer();
        js.append("<script>");
        js.append("window.location.href='").append(redirectUri).append("';");
        js.append("</script>");

        return js.toString();
    }
}
